<template>
  <v-chart
    :style="style"
    :option="widget.option"
    :update-options="{ notMerge: true }"
    autoresize
  />
</template>
<script>
import { renderWidgetData } from "../tools/DataUtils";
export default {
  props: {
    widget: {
      type: [Object],
      default: () => {},
    },
  },
  data() {
    return {
      render: null,
    };
  },
  computed: {
    style() {
      return {
        width: this.widget.location.width + "px",
        height: this.widget.location.height + "px",
      };
    },
    option() {
      return {
        customColor:
          this.widget.option.series[0].axisLine.lineStyle.customColor,
        customOffsetCenter:
          this.widget.option.series[0].detail.customOffsetCenter,
      };
    },
    data() {
      return this.widget.data;
    },
    refresh() {
      return this.widget.service.timestamp;
    },
  },
  watch: {
    option: {
      handler(val) {
        this.widget.option.series[0].axisLine.lineStyle.color = [
          [1, val.customColor],
        ];
        this.widget.option.series[0].detail.offsetCenter[0] =
          val.customOffsetCenter[0] + "%";
        this.widget.option.series[0].detail.offsetCenter[1] =
          val.customOffsetCenter[1] + "%";
      },
      deep: true,
    },
    data: {
      handler() {
        this.refreshWidgetInfo();
      },
      deep: true,
    },
    refresh: {
      handler() {
        this.refreshWidgetInfo();
      },
    },
  },
  mounted() {
    this.refreshWidgetInfo();
  },
  destroyed() {
    this.recoveryRenderObject();
  },
  methods: {
    refreshWidgetInfo() {
      this.recoveryRenderObject();
      this.render = renderWidgetData(this.widget, this.refreshWidgetData);
    },
    refreshWidgetData(data) {
      const option = this.widget.option;
      option.series[0].min = data.min;
      option.series[0].max = data.max;
      option.series[0].detail.formatter = "{value}" + data.unit;
      option.series[0].data[0].name = data.name;
      option.series[0].data[0].value = data.value;
    },
    recoveryRenderObject() {
      if (this.render && this.render.apiTimer) {
        clearInterval(this.render.apiTimer);
        this.render.apiTimer = null;
      }
      if(this.render && this.render.websocket) {
        this.render.websocket.doDisconnect();
      }
    },
  },
};
</script>